package com.yiyukongjian.house;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.yiyukongjian.house.dataaccess.HouseInforDataAccessor;
import com.yiyukongjian.house.dataaccess.HouseInforDataAccessorFactory;
import com.yiyukongjian.house.widget.TopNavigator;
/**
 * 显示列表信息，数据层得到的数据为K-V链表形式
 * @author baogang
 *
 */
public class ListGeneralResultActivity extends Activity {

	private ArrayList<HashMap<String,?>> mData = null;
	
	private HashMap<String, String> mSearchConditions = null;
	
	private int mCurrentFromID = 0;
	
	private int mCntPerQuery = 0;
	
	private BaseAdapter mAdapter = null;
	
	private static final int[] COLORS = {R.color.list_odd_backgroud,R.color.list_even_backgroud};
	@SuppressWarnings("unchecked")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_list_general_result);
//		Log.i(TAG, .toString());
		mData = (ArrayList<HashMap<String, ?>>) getIntent().getExtras().get(HouseConstants.KEY_RESULT);
		//持久化当前查询条件以便在本Activity进行更多数据的查询
		mSearchConditions =  (HashMap<String, String>) getIntent().getExtras().get(HouseConstants.KEY_SEARCH_CONDITION);
		mCurrentFromID = Integer.parseInt(mSearchConditions.get(HouseConstants.KEY_QUERY_FROM));
		mCntPerQuery = Integer.parseInt(mSearchConditions.get(HouseConstants.KEY_CNT_PER_QUERY));
		TopNavigator tng = (TopNavigator) findViewById(R.id.general_nav);
		tng.addListernOnLeftComponent(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
//				Log.i(TAG, "Click Return Btn From List Activity");
				
			}
		});		
//		List<Map<String,?>> content = (List<Map<String, ?>>) getIntent().getExtras().get(HouseConstants.KEY_RESULT_KEY);
		ListView lv = (ListView) findViewById(R.id.list_general_result);
		View footerView = ((LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE)).inflate(R.layout.general_list_footer, null, false);
        lv.addFooterView(footerView);        
//        View headerView = ((LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE)).inflate(R.layout.general_list_header, null, false);
//        lv.addHeaderView(headerView);
        mAdapter = new ListGeneralResultAdapter(mData,this);
		lv.setAdapter(mAdapter);
		footerView.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
//				if(mSearchConditions != null){	
//					if(mData != null){
//						HouseInforDataAccessor dataAccessor = HouseInforDataAccessorFactory.getHouseDataAccessor(0);
//						//计算取得数据开始的主键
//						mSearchConditions.put(HouseConstants.KEY_QUERY_FROM,mCurrentFromID + mCntPerQuery + "");
//						HashMap<String,?> result = dataAccessor.queryGeneralHouseInformation(mSearchConditions);
//						if(result.containsKey(HouseConstants.KEY_RESULT_SUCCESS)){
//							mData.addAll((ArrayList<HashMap<String,?>>)result.get(HouseConstants.KEY_RESULT_SUCCESS));
//							//如果查询成功，更新当前FromID；如果不成功保持原来FromID
//							mCurrentFromID += mCntPerQuery;
//							//成功则更新当前Listview
//							if(mAdapter != null){
//								mAdapter.notifyDataSetChanged();
//							}
//						}else if(result.containsKey(HouseConstants.KEY_RESULT_ERROR)){
//							Toast.makeText(ListGeneralResultActivity.this,result.get(HouseConstants.KEY_RESULT_ERROR).toString(), Toast.LENGTH_SHORT).show();
//						}
//					}			
//					
//				}
				new QueryMoreListDataTask().execute((Void)null);
			}
		});
	}
	
	/**
	 * 异步执行取得更多记录的查询
	 * @author baogang
	 *
	 */
	private class QueryMoreListDataTask extends AsyncTask<Void,Void,HashMap<String,?>>{

		@Override
		protected HashMap<String,?> doInBackground(Void... params) {
			System.out.println("Query more lists");
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
			if(mSearchConditions != null && mData != null){
				HouseInforDataAccessor dataAccessor = HouseInforDataAccessorFactory.getHouseDataAccessor(0);
				//计算取得数据开始的主键
				mSearchConditions.put(HouseConstants.KEY_QUERY_FROM,mCurrentFromID + mCntPerQuery + "");
				return dataAccessor.queryGeneralHouseInformation(mSearchConditions);
//				if(result.containsKey(HouseConstants.KEY_RESULT_SUCCESS)){
//					mData.addAll((ArrayList<HashMap<String,?>>)result.get(HouseConstants.KEY_RESULT_SUCCESS));
//					//如果查询成功，更新当前FromID；如果不成功保持原来FromID
//					
//				}else if(result.containsKey(HouseConstants.KEY_RESULT_ERROR)){
//					re = false;
//				}
			}
			return null;
//			return re;
		}

		@SuppressWarnings("unchecked")
		@Override
		protected void onPostExecute(HashMap<String,?> result) {
			System.out.println("on post execute...");
			if(result != null){
				if(result.containsKey(HouseConstants.KEY_RESULT_SUCCESS)){
					mData.addAll((ArrayList<HashMap<String,?>>)result.get(HouseConstants.KEY_RESULT_SUCCESS));
					//如果查询成功，更新当前FromID；如果不成功保持原来FromID
					mCurrentFromID += mCntPerQuery;
					//成功则更新当前Listview
					if(mAdapter != null){
						mAdapter.notifyDataSetChanged();
					}
				}else if(result.containsKey(HouseConstants.KEY_RESULT_ERROR)){
					Toast.makeText(ListGeneralResultActivity.this,result.get(HouseConstants.KEY_RESULT_ERROR).toString(), Toast.LENGTH_SHORT).show();					
				}
			}else{
				Toast.makeText(ListGeneralResultActivity.this,"数据源错误", Toast.LENGTH_SHORT).show();
			}			
			super.onPostExecute(result);
		}		
	}
	/**
	 * 自定义返回键按钮，返回House应用主页
	 *  
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
		    //回到应用主页面
		    Intent intent = new Intent(ListGeneralResultActivity.this,Index.class);
		    this.startActivity(intent);
		}
		return super.onKeyDown(keyCode, event);
	}

	private class ListGeneralResultAdapter extends android.widget.BaseAdapter{

		private ArrayList<HashMap<String,?>> mData = null;
		private Context mContext = null;
		
		ListGeneralResultAdapter(ArrayList<HashMap<String,?>> data,Context context){
			this.mData = data;
			this.mContext = context;
		}
		
		@Override
		public int getCount() {
			return this.mData.size();
		}

		@Override
		public Object getItem(int position) {
			return this.mData.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
//			Log.d(TAG, "Position:" + position + " : " + String.valueOf(System.currentTimeMillis()));
		       ViewHolder holder;
		       if (convertView == null) {
		           final LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		           convertView = inflater.inflate(R.layout.query_general_item, null);
		           holder = new ViewHolder();
		           holder.fwdzTv = (TextView) convertView.findViewById(R.id.query_general_fwdz);
		           holder.fzxmTv = (TextView) convertView.findViewById(R.id.query_general_fzxm);
		           holder.fzzjhmTv = (TextView) convertView.findViewById(R.id.query_general_fzzjhm);
		           holder.fzdhTv = (TextView) convertView.findViewById(R.id.query_general_fzdh);
		           holder.czrxmTv = (TextView) convertView.findViewById(R.id.query_general_czrxm);
		           holder.czrzjhmTv = (TextView) convertView.findViewById(R.id.query_general_czrzjhm);
		           holder.czrdhTv = (TextView) convertView.findViewById(R.id.query_general_czrdh);
		           holder.qzrqTv = (TextView) convertView.findViewById(R.id.query_general_qzrq);
		           holder.tzrqTv = (TextView) convertView.findViewById(R.id.query_general_tzrq);
		           holder.djrxmTv = (TextView) convertView.findViewById(R.id.query_general_djrxm);
		           holder.fwPKTv = (TextView) convertView.findViewById(R.id.query_general_pk);
		           convertView.setTag(holder);
		       } else {
		           holder = (ViewHolder) convertView.getTag();
		       }
               holder.fwdzTv.setText(mData.get(position).get(HouseConstants.KEY_FWDZ).toString());
               holder.fzxmTv.setText(mData.get(position).get(HouseConstants.KEY_FZXM).toString());
               holder.fzzjhmTv.setText(mData.get(position).get(HouseConstants.KEY_FZZJHM).toString());
               holder.fzdhTv.setText(mData.get(position).get(HouseConstants.KEY_FZLXDH).toString());
               holder.czrxmTv.setText(mData.get(position).get(HouseConstants.KEY_CZRXM).toString());
               holder.czrzjhmTv.setText(mData.get(position).get(HouseConstants.KEY_CZRZJHM).toString());
               holder.czrdhTv.setText(mData.get(position).get(HouseConstants.KEY_CZRLXDH).toString());
               holder.qzrqTv.setText(mData.get(position).get(HouseConstants.KEY_QZRQ).toString());
               holder.tzrqTv.setText(mData.get(position).get(HouseConstants.KEY_TZRQ).toString());
               holder.djrxmTv.setText(mData.get(position).get(HouseConstants.KEY_DJRXM).toString());
               holder.fwPKTv.setText(mData.get(position).get(HouseConstants.KEY_ID).toString());
               
               convertView.setBackgroundResource(COLORS[position % 2]);
               return convertView;
		}		
	}
	
	static class ViewHolder{
		//房屋地址
		TextView fwdzTv;
		//房主姓名
		TextView fzxmTv;
		//房主证件号码
		TextView fzzjhmTv;
		//房主电话
		TextView fzdhTv;
		//承租人姓名
		TextView czrxmTv;
		//承租人证件号码
		TextView czrzjhmTv;
		//承租人电话
		TextView czrdhTv;
		//起租日期
		TextView qzrqTv;
		//停租日期
		TextView tzrqTv;
		//登记人姓名
		TextView djrxmTv;
		//隐藏列主键
		TextView fwPKTv;
	}

}
